package com.zlz.mapreduce.joinPre;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

/**
 * @author: zlz
 * @date: 2022/1/3 12:17
 * @description:
 * @since: JDK1.8
 */
public class TableMapper extends Mapper<LongWritable, Text, Text, TableBean> {
    private String tableName;
    private Text outK = new Text();
    private TableBean outV = new TableBean();
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        FileSplit inputSplit = (FileSplit)context.getInputSplit();
        tableName = inputSplit.getPath().getName();
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 获取一行的数据
        String line = value.toString();

        // 格式化 将\t替换为空格
        String replace = line.replace("\t", StringUtils.SPACE);

        // 切割
        String[] split = StringUtils.split(replace, StringUtils.SPACE);
        if (tableName.contains(EnumTable.ORDER.getName())) {
//            1001    01  1
            outK.set(split[1]);
            outV.setId(split[0]);
            outV.setPid(split[1]);
            outV.setAmount(Integer.parseInt(split[2]));
            outV.setPname(StringUtils.EMPTY);
            outV.setTableName(EnumTable.ORDER.getName());
        } else {
//            01  小米
            outK.set(split[0]);
            outV.setId(StringUtils.EMPTY);
            outV.setPid(split[0]);
            outV.setAmount(-1);
            outV.setPname(split[1]);
            outV.setTableName(EnumTable.PRODUCT.getName());

        }
        context.write(outK, outV);
    }
}
